"""Main Controller"""
from catwalk.tg2 import Catwalk
from docutils.core import publish_parts
from pydive import model
from pydive.controllers.crud.news import NewsController
from pydive.controllers.crud.user import UserController
from pydive.controllers.crud.diver import DiverController
from pydive.controllers.error import ErrorController
from pydive.controllers.logbook import LogBookController
from pydive.controllers.profile import ProfileController
from pydive.controllers.secure import SecureController
from pydive.controllers.sites import SitesController
from pydive.lib.base import BaseController
from pydive.model import DBSession, metadata
from pydive.model.auth import User
from pydive.model.news import News
from pylons.i18n import ugettext as _
from repoze.what import predicates
from sqlalchemy.orm import eagerload
from tg import expose, flash, require, url, request, redirect, session
#import crud controllers
import logging
log = logging.getLogger(__name__)



class RootController(BaseController):
    admin = Catwalk(model, DBSession)
    error = ErrorController()
    secure = SecureController()
    sites = SitesController()
    profile = ProfileController()
    logbook = LogBookController()
    #crud controllers
    user = UserController(DBSession)
    news = NewsController(DBSession)
    diver = DiverController(DBSession)

    
    @expose('pydive.templates.index')
    def index(self):
        news = News().first(5);
        return dict(page='index',news=news)
    
    @expose('pydive.templates.test')
    def test(self):
        return dict(page='index')
    
    
    @expose('pydive.templates.register')
    def register(self):
        return dict(page='about')

    @expose('pydive.templates.about')
    def about(self):
        return dict(page='about')

    @expose('pydive.templates.login')
    def login(self, came_from=url('/')):
        login_counter = request.environ['repoze.who.logins']
        if login_counter > 0:
            flash(_('Wrong credentials'), 'warning')
        return dict(page='login', login_counter=str(login_counter),
                    came_from=came_from)

    @expose()
    def post_login(self, came_from=url('/')):
        if not request.identity:
            login_counter = request.environ['repoze.who.logins'] + 1
            redirect(url('/login', came_from=came_from, __logins=login_counter))
        userid = request.identity['repoze.who.userid']
        flash(_('Welcome back, %s!') % userid)
        
        u = DBSession.query(User).options(eagerload('diver')).filter(User.user_name == userid).all()[0]
        session['user'] = u
        session.save()
        log.debug("Logged in user :"+str(u))
        redirect(came_from)

    @expose()
    def post_logout(self, came_from=url('/')):
        flash(_('We hope to see you soon!'))
        log.debug("Logged out user :"+str(session['user']))
        del session['user']
        session.save()
        redirect('/')
        
        
        
